package com.espirit.eap.manager;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.hibernate.EmptyInterceptor;
import org.hibernate.Interceptor;
import org.hibernate.type.Type;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.googlecode.cswish.model.Saas;
import com.googlecode.cswish.struts.ContextHolder;
import com.googlecode.cswish.struts.spring.CacheService;
import com.googlecode.cswish.struts.spring.CacheService.Wrapper;
import com.googlecode.cswish.struts.spring.ObjectFactory;

@Service
@Lazy(value=false)
public class EntityInterceptor extends EmptyInterceptor {
	private static final long serialVersionUID = -3866216564373707403L;

	@Resource
	private CacheService cacheService;
	
	// hibernate instance and the spring instance share the variable
	private static Wrapper<Interceptor> interceptorWrapper;
	
	@PostConstruct
	private void init() {
		if (interceptorWrapper != null) {
			interceptorWrapper = cacheService.newVar(Interceptor.class);
		}
	}
	
	// register current site interceptor
	public void setInterceptor(Interceptor interceptor) {
		interceptorWrapper.set(interceptor);
	}

	public boolean onSave(Object entity, Serializable id, Object[] state,
			String[] propertyNames, Type[] types) {
		if (interceptorWrapper == null) {
			cacheService = ObjectFactory.getInstance().getBean(CacheService.class, true);
			interceptorWrapper = cacheService.newVar(Interceptor.class);
		}
		
		if (entity instanceof Saas){
			Saas saas = (Saas) entity;
			Integer sid = ContextHolder.get().getSid();
			if (sid != null){
				saas.setSid(sid);
			}
		}
		
		Interceptor interceptor = interceptorWrapper.get();
		if (interceptor != null) {
			return interceptor.onSave(entity, id, state, propertyNames, types);
		} else {
			return false;
		}
	}
	
	@Override
	public boolean onFlushDirty(Object entity, Serializable id,
			Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		if (interceptorWrapper == null) {
			cacheService = ObjectFactory.getInstance().getBean(CacheService.class, true);
			interceptorWrapper = cacheService.newVar(Interceptor.class);
		}
		
		Interceptor interceptor = interceptorWrapper.get();
		if (interceptor != null) {
			return interceptor.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
		} else {
			return false;
		}
	}
	
	@Override
	public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		if (interceptorWrapper == null) {
			cacheService = ObjectFactory.getInstance().getBean(CacheService.class, true);
			interceptorWrapper = cacheService.newVar(Interceptor.class);
		}
		
		Interceptor interceptor = interceptorWrapper.get();
		if (interceptor != null) {
			interceptor.onDelete(entity, id, state, propertyNames, types);
		} 
	}

}
